<?php

class Packing_listController extends Controller {
    const PAGE_SIZE=10;

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
        	'accessControl', // perform access control for CRUD operations
        	'AjaxOnly + companycreate,checkcargo,ajaxvalidatecargo',
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
        	array('allow',  // allow all users to perform 'index' and 'view' actions
        		'actions'=>array('index','view'),
        		'users'=>array('*'),
        	),
        	array('allow', // allow authenticated user to perform 'create' and 'update' actions
        		'actions'=>array('create','update','checkcargo','companycreate','updatepackage','ajaxvalidatecargo','viewpackage','newpackage','report'),
        		'users'=>array('@'),
        	),
        	array('allow', // allow admin user to perform 'admin' and 'delete' actions
        		'actions'=>array('admin','delete'),
        		'users'=>array('admin'),
        	),
        	array('deny',  // deny all users
        		'users'=>array('*'),
        	),
        );
    }

    /**
     * Displays a particular model.
     */
    public function actionView() {
        $this->BreadCrumbs(array('Packing List'=>'packing_list/view'),true);
        $this->render('view',array(
            'model'=>$this->loadModel(),
        	'packing_list_id'=>$_GET['id'],
        ));
    }
    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCompanyCreate() {
        $id = $_GET['id'];
        $name = company::model()->findByPk($id)->cname;
        switch($_GET['for']) {
            case "company": $select = "#packing_list_shipping_name";
                break;
            case "pod": $select = "#packing_list_pod_name";
                break;
        }
        echo "$('$select').val('$name');$('#packing_list_shipping_id').val('$id');";
    }
    public function actionReport() {
    	$packing_list = $this->loadModel();
    	//$this->render('report/packing_list');
    	if(Yii::app()->request->isAjaxRequest)
    		echo $this->renderPartial('_report', array('packing_list'=>$packing_list), true, true);
    	else
    		$this->render('_viewreport',array('packing_list'=>$packing_list));
    }
    public function actionGenerateDefaultReport() {
    	$packing_list = $this->loadModel();
    }
    public function actionNewPackage() {
        $package = new packing_list_packages;
        $package->packing_list_id = $_GET['packing_list_id'];
        $package->cargo[] = new cargo;
        $this->makeSubmitScript();
        if(isset($_POST['packing_list_packages'])) {
            $package->attributes = $_POST['packing_list_packages'];
            
            $this->AssignData($package->cargo,'packing_list_packages_cargo');
            
            if(!$package->savePackages(true)) {
                $err = $this->getErrorName(array($package,$package->cargo));
                echo CJavaScript::jsonEncode(array('attr'=>$err['attr'],'summary'=>$err['summary']));
            }
            else
            	echo CJavaScript::jsonEncode(array('id'=>$package->id));
            return;
        }
        echo $this->renderPartial('updatepackage',array('item'=>$package),true,true);
    }
    public function actionUpdatePackage() {
        $id = $_GET['id'];
        $package = packing_list_packages::model()->findByPk($id);
        $package->cargo = $package->cargo();
        $package->cargo[] = new packing_list_packages_cargos;
        $this->makeSubmitScript();
        if(isset($_POST['packing_list_packages'])) {
            $package->attributes = $_POST['packing_list_packages'];
           	$this->AssignData($package->cargo,'packing_list_packages_cargos');
            if(!$package->savePackages(true)) {
                $err = $this->getErrorName(array($package,$package->cargo));
                echo CJavaScript::jsonEncode(array('attr'=>$err['attr'],'summary'=>$err['summary']));
            }
            return;
        }
        if($package!==NULL) {
            echo $this->renderPartial('updatepackage', array('item'=>$package), true, true);
        }
    }
    public function actionViewPackage() {
        $id = $_GET['id'];
        $package = packing_list_packages::model()->findByPk($id);
        foreach($package->cargo() as $cargo) {
            $package->do_list[] = $cargo->ref_no;
        }
        echo $this->renderPartial('_viewpackingform',array('package'=>$package),true,true);
    }
    public function actionajaxValidateCargo() {
        $cargo = $_GET['c'];
        $p = $_GET['p'];
        $package_id = isset($_GET['id'])?$_GET['id']:0;
        
        $packing_list = packing_list::model()->findByPk($p);
        $date = $packing_list->date;
        $cargoID = 0;
        $s = $this->validateCargo($cargo, $date, &$cargoID);
        $newcargo = CHtml::normalizeUrl(array('cargo/create','ref_no'=>$cargo));
        $usedcargo = CHtml::normalizeUrl(array('cargo/update','id'=>$cargoID));
        $qty = 0;
        if($cargoID > 0) {
            $_c = cargo::model()->findByPk($cargoID);
            $qty = $_c->getLeftOverQty();
        }
        echo CJavaScript::jsonEncode(array('r'=>$s,'n'=>$newcargo,'u'=>$usedcargo,'id'=>$cargoID,'qty'=>$qty));
    }
    private function validateCargo($ref,$date,&$cargoID) {
        if(is_numeric($date))
            $inputYear = date('Y',$date);
        else {
            $_date = explode("/", $date);
            $inputYear = date('Y',mktime(0,0,0,1,1,$_date[2]));
        }
        $cargo=cargo::model()->with('qty')->find("replace(upper(ref_no),' ','')=:ref_no AND from_unixtime(in_date,'%Y')=:year",array(':ref_no'=>str_replace(' ','',strtoupper($ref)),':year'=>$inputYear));
        if($cargo==NULL) {
            $cargo=cargo::model()->with('qty')->find("replace(upper(ref_no),' ','')=:ref_no AND from_unixtime(in_date,'%Y')=:year AND packing_list_id<=0",array(':ref_no'=>str_replace(' ','',strtoupper($ref)),':year'=>$inputYear-1));
            if($cargo != NULL) {
                //cargo found in previous year
                $cargoID = $cargo->id;
                $cargo->setScenario("packing_list");
                if($cargo->validate())
                    return 3; // validate pass
                else
                    return 2; // validate fail
            }
            else {
                $cargoID = 0;
                return 0; //no cargo found
            }
        }
        else {
            $cargoID = $cargo->id;
            $cargo->setScenario("packing_list");
                if($cargo->validate())
                    return 4; //validate pass
                else
                    return 1; // validate fail
        }
        return 0;
    }
    public function actionCheckCargo() {
        $packing_list = array(); // cargo ref no found but already have packing list, meaning shiped out
        $noDO = array(); // totally no cargo_ref found in database
        $prevDO = array(); // no cargo ref_no found in current but found in prev year
        $_date = explode("/", $_POST['packing_list']['date']);
        $inputYear = date('Y',mktime(0,0,0,1,1,$_date[2]));
        foreach($_POST['packing_list_packages'] as $item) {
            foreach($item['do_list'] as $dos) {
                if(!empty($dos)) {
                    $cargos=cargo::model()->findAll("replace(upper(ref_no),' ','')=:ref_no",array(':ref_no'=>str_replace(' ','',strtoupper($dos))));
                    if(count($cargos)>0) {
                        $found = false;
                        foreach($cargos as $cargo) {
                            $dataYear = date('Y', $cargo->in_date);
                            if($dataYear == $inputYear) {
                                if($cargo->packing_list_id > 0) {
                                    if(!in_array($dos,$packing_list))
                                        $packing_list[] = $dos;
                                }
                                $found = true;
                            }
                        }
                        if(!$found && count($cargo)>0) {
                            if(!in_array($dos,$prevDO))
                                $prevDO[] = $dos;
                        }
                    }
                    else {
                        if(!in_array($dos,$noDO))
                            $noDO[] = $dos;
                    }
                }
            }
        }
        $returnVal = "$.ajax({url: 'http://spartan.noads.biz/index.php/packing_list/create',dataType: 'script', data: $('form').serialize(), type: 'POST'});";
        if(count($noDO)>0||count($prevDO)>0||count($packing_list)>0) {
            $error = $this->makeErrorByValue($noDO).$this->makeErrorByValue($prevDO).$this->makeErrorByValue($packing_list);
            $noDO = (count($noDO)>0)?implode(',',$noDO).' - No DO is found in database.':'';
            $prevDO = (count($prevDO)>0)?implode(',',$prevDO).' - DO is not found in current year but in previous year.':'';
            $packing_list = (count($packing_list)>0)?implode(',',$packing_list).' - DO is already being shipped out.':'';
            $error .=$this->makeJsErrorMsg(array($noDO,$prevDO,$packing_list));
            $returnVal = "confirmBox({title:'Error cargo ref found!',msg:'There is some errors in the DO numbers entered. Do you wish to change the DO number or continue, by continuing, the system will make the decision.',buttons:{'Continue':function(){ $(this).dialog('close');$returnVal},'Change':function(){ $(this).dialog('close');$error}}});";
        }
        echo $returnVal;
    }
    private function returnCargoID($cargo = array(),$inputYear) {
        $IDs = array();
        foreach($cargo as $dos) {
            if(!empty($dos)) {
            //find current year cargo
                $cargo=cargo::model()->find("replace(upper(ref_no),' ','')=:ref_no AND from_unixtime(in_date,'%Y')=:year",array(':ref_no'=>str_replace(' ','',strtoupper($dos)),':year'=>$inputYear));
                if($cargo != null) {
                    $IDs[] = $cargo->id;
                }
                else {
                //find prev year cargo with no packing ID
                    $cargo=cargo::model()->find("replace(upper(ref_no),' ','')=:ref_no AND from_unixtime(in_date,'%Y')=:year AND packing_list_id<=0",array(':ref_no'=>str_replace(' ','',strtoupper($dos)),':year'=>$inputYear-1));
                    if($cargo != null) {
                        $IDs[] = $cargo->id;
                    }
                    else {
                    // Add new cargo
                        $cargo = new cargo;
                        $cargo->ref_no = $dos;
                        $cargo->in_date = time();
                        if($cargo->save(false)) {
                            $IDs[] = $cargo->id;
                        }
                    }
                }
            }
        }
        return $IDs;
    }
    public function actionCreate() {
        $packinglist = new packing_list;
        $packinglist->packages[0] = new packing_list_packages;
        $packinglist->packages[0]->do_list[0]='';
        $this->getReferrer('packing_list');
        $this->makeSubmitScript();
        if(isset($_POST['packing_list'])) {
            $packinglist->attributes=$_POST['packing_list'];
            $this->AssignData(&$packinglist->packages, 'packing_list_packages');
            foreach($packinglist->packages as $package) {
                $_date = explode("/", $packinglist->date);
                $inputYear = date('Y',mktime(0,0,0,1,1,$_date[2]));
                $package->cargo_id = $this->returnCargoID($package->do_list,$inputYear);
            }
            $transaction = Yii::app()->db->beginTransaction();
            if($packinglist->savePackingList()) {
                $transaction->commit();
                if(!Yii::app()->request->isAjaxRequest)
                    $this->redirect(array('view','id'=>$packinglist->id));
            }
            else {
                $transaction->rollback();
                if(Yii::app()->request->isAjaxRequest) {
                    if($packinglist->hasErrors('shipping_id'))
                        $packinglist->addError('shipping_name', "");
                    if($packinglist->hasErrors('pod'))
                        $packinglist->addError('pod_name', "");
                    $err = $this->getErrorName($packinglist);
                    echo CJavaScript::jsonEncode(array('attr'=>$err['attr'],'summary'=>$err['summary']));
                }

            }
        //if($model->save())
        // $this->redirect(array('view','id'=>$model->id));
        }
        if(!Yii::app()->request->isAjaxRequest) {
            $this->render('create',array(
                'model'=>$packinglist,
            ));
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     */
    public function actionUpdate() {
        $model=$this->loadModel();
        if(isset($_POST['packing_list'])) {
            $model->attributes=$_POST['packing_list'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('update',array(
            'model'=>$model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     */
    public function actionDelete() {
        if(Yii::app()->request->isPostRequest) {
        // we only allow deletion via POST request
            $this->loadModel()->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_POST['ajax']))
                $this->redirect(array('index'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider=new CActiveDataProvider('packing_list', array(
            'pagination'=>array(
            'pageSize'=>self::PAGE_SIZE,
            ),
        ));

        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $dataProvider=new CActiveDataProvider('packing_list', array(
            'pagination'=>array(
            'pageSize'=>self::PAGE_SIZE,
            ),
        ));

        $this->render('admin',array(
            'dataProvider'=>$dataProvider,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel() {
        if($this->_model===null) {
            if(isset($_GET['id']))
                $this->_model=packing_list::model()->findbyPk($_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

    private function checkDO($DORef, $getYear=null) {
        $criteria = new CDbCriteria;
        if($getYear===null) {
            $criteria->condition = 'replace(upper(t.ref_no)," ","") = replace(upper(:ref_no)," ","")';
            $criteria->order = 't.in_date desc';

        }
        else {
            $getYear=mktime(0,0,0,1,1,$getYear);
            $criteria->condition = 'replace(upper(t.ref_no)," ","") = replace(upper(:ref_no)," ","") and t.in_date >= :in_date';
        }
        $criteria->params = array(':ref_no'=>$DORef,':in_date'=>$getYear);
        return cargo::model()->find($criteria);
    }
}
